package com.retail.lottery.colalottery.aop;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.retail.lottery.colalottery.config.NeedCryptoConfig;
import com.retail.lottery.colalottery.enums.CommonEnum;
import com.retail.lottery.colalottery.utils.AesUtil;
import com.retail.lottery.colalottery.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * 请求数据接收处理类
 * 对加了@Decrypt的方法的数据进行解密操作
 *
 * @author zy
 */
@ControllerAdvice
@Slf4j
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {

    @Value("${aes-key}")
    public String aesKsy;
    @Value("${aes-iv}")
    public String aesIv;
    public static final String ENCRYPT_DATA = "encryptData";

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return new NeedCryptoConfig().isNeedDecrypt(methodParameter);
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                           Class<? extends HttpMessageConverter<?>> converterType) {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        String jsonStr = null;
        try {
            // 解密操作
            if(body instanceof String){
                JSONObject encryptObject = JSONObject.parseObject(body.toString());
                String srcData = String.valueOf(encryptObject.get(ENCRYPT_DATA));
                jsonStr =AesUtil.decryptBase64(srcData, aesKsy, aesIv);
            }
        } catch (Exception e) {
            log.error("请求body参数格式解析异常！", e);
        }
        return jsonStr;
    }
}
